/**
 * @file add_two_number.cpp
 * @author mixinju@outlook.com
 * @brief 题目来源与LeetCode 2
 * 觉得这个题对于处理两个链表的问题，以及大数相加的算法很有启发性
 * @version 0.1
 * @date 2021-11-20
 *
 * @copyright Copyright (c) 2021
 *
 */

//题目地址 https://leetcode-cn.com/problems/add-two-numbers/submissions/
#include "list.h"
ListNode* addTwoNumbers(ListNode* first, ListNode* second) {
  ListNode* dummy = new ListNode();
  ListNode* pre = dummy;
  // TODO:记得要把记录进位的变量定义在循环的外面
  int carry = 0;
  while (first || second) {
    int one = (first) ? first->data_ : 0;
    int two = (second) ? second->data_ : 0;

    if (first) {
      pre->next_ = first;
      first = first->next_;
    }
    if (second) {
      pre->next_ = second;
      second = second->next_;
    }

    pre = pre->next_;
    pre->data_ = (carry + one + two) % 10;
    carry = (carry + one + two) / 10;
  }
  if (carry) {
    pre->next_ = new ListNode(carry);
  } else {
    pre->next_ = nullptr;
  }

  return dummy->next_;
}
